﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting.Internal;
using Microsoft.Extensions.Logging;
using StudentManagement.Models;
using StudentManagement.ViewModels;

namespace StudentManagement.Controllers
{
    //[Route("Home")]
    //[Authorize]
    public class HomeController : Controller
    {
        private readonly IStudentRepository _studentRepository;
        private IWebHostEnvironment webHostEnvironment;
        private ILogger<HomeController> logger;

        /// <summary>
        /// 使用构造函数注入IStudentRepository
        /// </summary>
        /// <param name="studentRepository"></param>
        public HomeController(IStudentRepository studentRepository,IWebHostEnvironment webHostEnvironment,ILogger<HomeController> logger)
        {
            _studentRepository = studentRepository;
            this.webHostEnvironment = webHostEnvironment;
            this.logger = logger;
        }

        //public string Index()
        //{
        //    //返回学生的名字
        //    return _studentRepository.GetStudent(1).Name;
        //    //return Json(new {id = "1", name = "张三"});
        //}

        //[Route("")]
        //[Route("Index")]
        //[Route("~/")]
        public IActionResult Index()
        {
            var students = _studentRepository.GetAllStudents();
            return View(students);
        }

        //public JsonResult Details()
        //{
        //    var model = _studentRepository.GetStudent(1);
        //    return Json(model);
        //}

        //public ObjectResult Details()
        //{
        //    var model = _studentRepository.GetStudent(1);
        //    return new ObjectResult(model);
        //}

        //[Route("Details/{id?}")]
        //[AllowAnonymous]
        public IActionResult Details(int id)
        {
            //var model = _studentRepository.GetStudent(1);

            //ViewData["PageTitle"] = "学生详情";
            //ViewData["Student"] = model;

            ////将PageTitle和Student模型对象存储在ViewBag
            ////我们正在使用动态属性PageTitle和Student
            //ViewBag.PageTitle = "学生详情";
            //ViewBag.Student = model;

            //实例化HomeDetailsViewModel并存储Student详细信息和PageTitle

            logger.LogTrace("Trace(跟踪) Log");
            logger.LogDebug("Debug(调试) Log");
            logger.LogInformation("信息(Information) Log");
            logger.LogWarning($"警告(Warning) Log");
            logger.LogError($"错误(Error) Log");
            logger.LogCritical("严重(Critical) Log");

            //throw new Exception("此异常发生在Details视图中");

            var student = _studentRepository.GetStudent(id);

            if (student == null)
            {
                Response.StatusCode = 404;

                return View("StudentNotFound", id);
            }

            var homeDetailsViewModel = new HomeDetailsViewModel()
            {
                Student = student,
                PageTitle = "学生详细信息"
            };

            //return View("~/MyViews/Test.cshtml");
            return View(homeDetailsViewModel);
        }

        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }

        //[HttpPost]
        //public RedirectToActionResult Create(Student student)
        //{
        //    var newStudent = _studentRepository.Add(student);
        //    return RedirectToAction("Details", new {id = newStudent.Id});
        //}

        [HttpPost]
        public IActionResult Create(StudentCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = null;
                if (model.Photos != null && model.Photos.Count > 0)
                {
                    uniqueFileName = ProcessUploadedFile(model);
                }
                var newStudent = new Student()
                {
                    Name = model.Name,
                    Email = model.Email,
                    ClassName = model.ClassName,
                    PhotoPath = uniqueFileName
                };
                _studentRepository.Add(newStudent);
                //var newStudent = _studentRepository.Add(student);
                return RedirectToAction("Details",new {id = newStudent.Id});
            }

            return View();
        }

        //1、视图
        //视图模型
        //2、对应的页面调整
        [HttpGet]
        public ViewResult Edit(int id)
        {
            var student = _studentRepository.GetStudent(id);

            //if (student != null)
            //{
                var studentEditViewModel = new StudentEditViewModel()
                {
                    Id = student.Id,
                    Name = student.Name,
                    Email = student.Email,
                    ClassName = student.ClassName,
                    ExistingPhotoPath = student.PhotoPath
                };

                return View(studentEditViewModel);
            //}

            //throw new Exception("查询不到这个学生信息");
        }

        [HttpPost]
        public IActionResult Edit(StudentEditViewModel model)
        {
            //检查提供的数据是否有效，如果没有通过验证，需要重新编辑学生信息
            //这样用户就可以更正并重新提交编辑表单
            if (ModelState.IsValid)
            {
                var student = _studentRepository.GetStudent(model.Id);
                student.Email = model.Email;
                student.Name = model.Name;
                student.ClassName = model.ClassName;
                if (model.Photos.Count > 0)
                {
                    if (model.ExistingPhotoPath != null)
                    {
                        var filePath = Path.Combine(webHostEnvironment.WebRootPath, "images", model.ExistingPhotoPath);
                        System.IO.File.Delete(filePath);
                    }

                    student.PhotoPath = ProcessUploadedFile(model);
                }

                var updateStudent = _studentRepository.Update(student);

                return RedirectToAction("Index");
            }

            return View();
        }

        /// <summary>
        /// 将照片保存到指定的路径中，并返回唯一的文件名
        /// </summary>
        /// <returns></returns>
        private string ProcessUploadedFile(StudentCreateViewModel model)
        {
            string uniqueFileName = null;

            if (model.Photos.Count > 0)
            {
                foreach (var item in model.Photos)
                {
                    //必须将图像上传到wwwroot中的images文件夹
                    //而要获取wwwroot文件夹的路径，我们需要注入ASP.NET Core提供的IWebHostEnvironment服务
                    //通过IWebHostEnvironment服务去获取wwwroot文件夹的路径
                    var uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "images");
                    uniqueFileName = $"{Guid.NewGuid()}_{item.FileName}";
                    var filePath = Path.Combine(uploadsFolder, uniqueFileName);

                    //因为使用了非托管资源，所以需要手动进行释放
                    using var fileStream = new FileStream(filePath,FileMode.Create);
                    //使用IFormFile接口提供的CopyTo()方法将文件复制到wwwroot/images文件夹
                    item.CopyTo(fileStream);
                }
            }

            return uniqueFileName;
        }

    }
}